<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>会话管理 - 系统管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        .session-filter {
            background: #f8f8f8;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }

        .session-stats {
            margin-bottom: 15px;
        }

        .session-stats .layui-card-body {
            font-size: 16px;
            color: #333;
        }
    </style>
</head>

<body>
    <div class="layui-container">
        <div class="layui-card">
            <div class="layui-card-header">
                <span style="font-size: 18px; font-weight: bold;">会话管理</span>
                <div style="float: right;">
                    <button class="layui-btn layui-btn-sm" id="refreshBtn">
                        <i class="layui-icon layui-icon-refresh"></i>刷新
                    </button>
                </div>
            </div>
            <div class="layui-card-body" style="font-size: 14px;">
                <!-- 筛选区域 -->
                <div class="session-filter">
                    <div class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">用户筛选</label>
                            <div class="layui-input-inline">
                                <input type="text" id="userFilter" placeholder="用户ID" class="layui-input">
                            </div>
                            <button class="layui-btn layui-btn-normal" onclick="loadSessions()">查询</button>
                            <button class="layui-btn layui-btn-primary" onclick="clearFilter()">清空</button>
                        </div>
                    </div>
                </div>

                <!-- 统计信息 -->
                <div class="layui-row session-stats">
                    <div class="layui-col-md4">
                        <div class="layui-card">
                            <div class="layui-card-header">活跃会话</div>
                            <div class="layui-card-body" id="activeSessionCount" style="color: #5FB878;">
                                加载中...
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-card">
                            <div class="layui-card-header">总会话数</div>
                            <div class="layui-card-body" id="totalSessionCount" style="color: #1E9FFF;">
                                加载中...
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-card">
                            <div class="layui-card-header">今日登录</div>
                            <div class="layui-card-body" id="todayLoginCount" style="color: #FFB800;">
                                加载中...
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 会话表格 -->
                <table id="sessionTable" lay-filter="sessionTable"></table>
            </div>
        </div>
    </div>

    <!-- 会话操作工具栏模板 -->
    <script type="text/html" id="sessionToolbar">
        <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="close">终止会话</button>
    </script>

    <!-- 状态列模板 -->
    <script type="text/html" id="statusTpl">
        {{# if(d.status === 1){ }}
            <span class="layui-badge layui-bg-green">活跃</span>
        {{# } else { }}
            <span class="layui-badge layui-bg-gray">关闭</span>
        {{# } }}
    </script>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/js/auth-utils.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/utils.js"></script>

    <script>
        layui.use(['table', 'form', 'util'], function () {
            var table = layui.table;
            var form = layui.form;
            var util = layui.util;
            var bsm_utils = layui.bsm_utils;
            var layer = layui.layer;
            var $ = layui.$;

            // 初始化会话表格 - 改为手动数据加载
            function initSessionTable() {
                var loading = layer.load(1);

                http.get(API_CONFIG.ADMIN.SESSIONS + '?limit=1000')
                    .then(function (res) {
                        layer.close(loading);

                        table.render({
                            elem: '#sessionTable',
                            data: res.data,
                            page: true,
                            limits: [10, 20, 50],
                            limit: 10,
                            height: 500,
                            cols: [[
                                { type: 'numbers', title: '序号', width: "60", align: 'center' },
                                { field: 'user_id', title: '用户账号', width: 120 },
                                { field: 'ip_address', title: '登录IP', width: 160 },
                                {
                                    field: 'login_time',
                                    title: '登录时间',
                                    width: 180,
                                    templet: function (d) {
                                        return d.login_time ? util.toDateString(d.login_time) : '-';
                                    }
                                },
                                {
                                    field: 'last_active',
                                    title: '最后活动',
                                    width: 180,
                                    templet: function (d) {
                                        return d.last_active ? util.toDateString(d.last_active) : '-';
                                    }
                                },
                                {
                                    field: 'status',
                                    title: '状态',
                                    width: 80,
                                    align: 'center',
                                    templet: '#statusTpl'
                                },
                                {
                                    field: 'session_duration',
                                    title: '持续时间',
                                    width: 100,
                                    templet: function (d) {
                                        if (!d.login_time) return '-';
                                        var loginTime = new Date(d.login_time).getTime();
                                        var now = new Date().getTime();
                                        var duration = now - loginTime;
                                        var hours = Math.floor(duration / (1000 * 60 * 60));
                                        var minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
                                        return hours + 'h' + minutes + 'm';
                                    }
                                },
                                { fixed: 'right', title: '操作', toolbar: '#sessionToolbar', width: 120, align: 'center' }
                            ]]
                        });

                        // 更新统计信息
                        updateSessionStats(res.data);
                    })
                    .catch(function (err) {
                        layer.close(loading);
                        layer.msg('加载会话数据失败');
                    });
            }

            // 更新会话统计
            function updateSessionStats(sessions) {
                if (!sessions) return;

                var activeSessions = sessions.filter(s => s.status === 1).length;
                var totalSessions = sessions.length;

                // 计算今日登录数
                var today = new Date().toDateString();
                var todayLogins = sessions.filter(s => {
                    if (!s.login_time) return false;
                    var loginDate = new Date(s.login_time).toDateString();
                    return loginDate === today;
                }).length;

                document.getElementById('activeSessionCount').textContent = activeSessions;
                document.getElementById('totalSessionCount').textContent = totalSessions;
                document.getElementById('todayLoginCount').textContent = todayLogins;
            }

            // 初始化
            initSessionTable();

            // 会话表格工具条事件
            table.on('tool(sessionTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'close') {
                    terminateSession(data);
                }
            });

            // 绑定回车键搜索
            $('#userFilter').on('keydown', function (e) {
                if (e.keyCode === 13) {
                    loadSessions();
                }
            });

            // 加载会话数据
            window.loadSessions = function () {
                var userId = document.getElementById('userFilter').value;
                var url = API_CONFIG.ADMIN.SESSIONS + (userId ? '?user_id=' + userId + '&limit=1000' : '?limit=1000');

                var loading = layer.load(1);

                http.get(url)
                    .then(function (res) {
                        layer.close(loading);
                        table.reload('sessionTable', {
                            data: res.data
                        });

                        // 更新统计信息
                        updateSessionStats(res.data);

                        var msg = userId ?
                            `用户 ${userId} 的会话查询完成，找到 ${res.data.length} 条记录` :
                            `所有会话查询完成，共 ${res.data.length} 条记录`;
                        layer.msg(msg);
                    })
                    .catch(function (err) {
                        layer.close(loading);
                        layer.msg('查询失败: ' + (err.msg || err.message));
                    });
            }

            // 终止会话
            function terminateSession(sessionData) {
                const currentUser = window.authUtils.getCurrentUser();
                var sid = bsm_utils.getSessionId();

                if (sid === sessionData.session_id) {
                    layer.msg('不能终止当前会话，请使用登出功能', { icon: 2 });
                    return;
                }

                layer.confirm('确定终止该会话？<br>用户: ' + sessionData.user_id + '<br>IP: ' + sessionData.ip_address,
                    { icon: 3, title: '终止会话确认' }, function (index) {
                        var loading = layer.load(1);

                        http.delete(API_CONFIG.ADMIN.SESSIONS + '/' + sessionData.session_id)
                            .then(function (res) {
                                layer.close(loading);
                                layer.msg('会话终止成功');

                                // 重新加载数据
                                loadSessions();
                            })
                            .catch(function (err) {
                                layer.close(loading);
                                if (err.code === 404) {
                                    layer.msg('会话不存在或已被终止');
                                } else if (err.code === 403) {
                                    layer.msg('权限不足，无法终止该会话');
                                } else {
                                    layer.msg('终止会话失败: ' + (err.msg || '未知错误'));
                                }
                            })
                            .finally(function () {
                                layer.close(index);
                            });
                    });
            }

            // 刷新按钮事件
            $('#refreshBtn').on('click', function () {
                document.getElementById('userFilter').value = '';
                // 直接调用初始化函数重新加载
                initSessionTable();
            });

        });


        // 清空筛选条件
        window.clearFilter = function () {
            document.getElementById('userFilter').value = '';
            layui.loadSessions();
        }
    </script>
</body>

</html>